package org.springblade.modules.develop.beetl;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.FileResourceLoader;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.modules.develop.service.IProgrammeService;
import org.springblade.modules.develop.utils.FileUtils;
import org.springframework.core.env.Environment;

public abstract class GeneratorCode {
	public final static Logger logger=LoggerFactory.getLogger(GeneratorCode.class);
	/***模板路径****/
	private String templatePath;
	/***生成文件路径****/
	private String generatorFilePath;
	/***参数****/
	private Map<String, Object> paras;

	public GeneratorCode(){}
	
	public GeneratorCode(String templatePath,String generatorFilePath) {
		this.templatePath = templatePath;
		this.generatorFilePath=generatorFilePath;
	}

	public static String getTplPathPre() {
		return SpringUtil.getBean(Environment.class).getProperty("beetl.tpl.path");
	}

	public GroupTemplate getGroupTemplate() throws Exception {
		FileResourceLoader resourceLoader = new FileResourceLoader(getTplPathPre(), "utf-8");
//		Configuration cfg = Configuration.defaultConfiguration();
//		GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
		BeetlGroupUtilConfiguration cfg=new BeetlGroupUtilConfiguration();
		cfg.setResourceLoader(resourceLoader);
		Map<String, Object> functionPackages=new HashMap<>();
		functionPackages.put("sputil", new org.beetl.ext.spring.UtilsFunctionPackage());
		functionPackages.put("vueRender", new org.springblade.modules.develop.beetl.function.RenderFunction());
		cfg.setFunctionPackages(functionPackages);
		cfg.init();
		GroupTemplate gt = cfg.getGroupTemplate();
		return gt;
	}

	public void generator() throws Exception {
		GroupTemplate gt = getGroupTemplate();
		Template t = gt.getTemplate(templatePath);
		Map<String, Object> paras = getParas();
		t.fastBinding(paras);
		t.binding("programmeService",SpringUtil.getBean(IProgrammeService.class));
		//t.binding("programmeTableService",SpringUtil.getBean(IProgrammeTableService.class));
		FileUtils.createFile(generatorFilePath);
		FileOutputStream out = new FileOutputStream(generatorFilePath);
		t.renderTo(out);
		out.close();
	}

	public String getTemplatePath() {
		return templatePath;
	}

	public void setTemplatePath(String templatePath) {
		this.templatePath = templatePath;
	}

	public String getGeneratorFilePath() {
		return generatorFilePath;
	}

	public void setGeneratorFilePath(String generatorFilePath) {
		this.generatorFilePath = generatorFilePath;
	}

	public void setParas(Map<String, Object> paras) {
		this.paras = paras;
	}
	/**
	 * 模板需要的参数map
	 * @return
	 */
	public Map<String, Object> getParas(){
		return paras;
	}
}
